function generateCode() {

  const CHARS = '0123456789ABCDEFGHIJKLMNOPKRSTUVWXYZ'

  let code = ''
  for(let i = 0; i < 4; i++) {
    const rand = Math.floor(Math.random() * CHARS.length)
    code += CHARS[rand]
  }

  return code
}

function generateBg(width, height) {
  
  const ctx = uni.createCanvasContext('captcha')
  
    // 设置 canvas 宽高
    ctx.canvas.width = width 
    ctx.canvas.height = height


  ctx.rect(0, 0, width, height)
  ctx.setFillStyle('#fff')
  ctx.fill()

  return ctx.canvas
}

function splitImage(canvas, rows, cols) {

  // 获取 canvas 元素
    const ctx = uni.createCanvasContext('captcha') 
    const imgWidth = canvas.width
    const imgHeight = canvas.height

  const tileW = imgWidth / cols
  const tileH = imgHeight / rows  

  const pieces = []

  for(let r = 0; r < rows; r++) {
    for(let c = 0; c < cols; c++) {
      const tileData = ctx.getImageData(c*tileW, r*tileH, tileW, tileH)
      pieces.push(tileData)
    }
  }

  return pieces
}


function shuffle(pieces) {
  
  for(let i = pieces.length - 1; i > 0; i--){
    const j = Math.floor(Math.random() * (i + 1))
    const temp = pieces[i]
    pieces[i] = pieces[j]
    pieces[j] = temp
  }

  return pieces
}


export function generateCaptcha(width, height) {
	console.log('过来的高宽：', width, height)
  const code = generateCode()

  const ctx = uni.createCanvasContext('captcha')
  const bg = generateBg(width, height)

  const rows = 3
  const cols = 3
  const pieces = splitImage(bg, rows, cols)

  shuffle(pieces)

  return {
    text: code,
    bg,
    pieces
  }

}